package com.it.park.controller.expose;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.it.park.client.service.LoginLogService;
import com.it.park.client.service.MsgService;
import com.it.park.client.service.ProtocolService;
import com.it.park.client.service.UserMsgService;
import com.it.park.common.CreateLink;
import com.it.park.common.JsonObj;
import com.it.park.common.MD5;
import com.it.park.common.NameHelper;
import com.it.park.constant.Constant;
import com.it.park.model.LoginLog;
import com.it.park.model.Msg;
import com.it.park.model.Protocol;
import com.it.park.model.UserMsg;
import com.it.park.rms.client.model.User;
import com.it.park.rms.client.service.UserService;
import com.it.park.util.date.DateUtil;
import com.it.park.util.email.EmailUtil;
import com.it.park.util.image.ImageUtil;
import com.it.park.util.ip.IPUtil;

@Controller
public class LoginController {
	
	private String rootPath=Constant.EXPOSE_PATH;

	@Autowired
	private UserService userService;
	@Autowired
	private ProtocolService protocolService;
	@Autowired
	private UserMsgService userMsgService;
	@Autowired
	private MsgService msgService;
	@Autowired
	private LoginLogService loginLogService;
	/**
	 * 跳转到登陆页面
	 * @return
	 */
	@RequestMapping("/login")
	public String login(){
		return rootPath+"login";
	}
	
	/**
	 * 登录验证
	 **/
	@RequestMapping("checkLogin")
	@ResponseBody//将对象转化为json对象
	public JsonObj checkLogin(String username,String password,HttpServletRequest request,HttpSession session,HttpServletResponse response){
			JsonObj json = new JsonObj();
			User u= userService.login(username);
			String pwd = MD5.md5(password);
			Integer status=1;
			if(u != null){
				if(u.getPassword().equals(pwd)){
					boolean success = false ;
					String msg = "";
					switch(u.getDisabled()){
       			 	case -1:
       			 		status = -1;
       			 		msg = "账号未认证!";
       			 		break;
       			 	case 0:
       			 		status = 0;
       			 		msg = "账号已被锁定!";
       			 		break;
       			 	case 1:
       			 		success = true;
       			 		status = 1;
       			 		msg = "登陆成功!";
       			 		session.setAttribute("user", u);
       			 		//写登录日志
       			 		LoginLog loginLog = new LoginLog();
       			 		loginLog.setUserId(u.getId());
       			 		loginLog.setUsername(u.getUserName());
       			 		loginLog.setCreateDate(new Date());
       			 		loginLog.setIp(IPUtil.getIP(request));
       			 		loginLogService.insertSelective(loginLog);
       			 		break;
       			 	case 2:
       			 		status = 2;
       			 		msg = "你的账号还未激活,请进邮箱查看激活地址!";
       			 		break;
   				 }
					json.setSuccess(success);
					json.setMessage(msg);
					json.setObject(u);
					json.setCode(status);
				}else{
					json.setMessage("密码错误!");
					json.setCode(-2);
					json.setSuccess(false);
				}
			}else{
				json.setSuccess(false);
				json.setMessage("用户名不存在!");
				json.setCode(-3);
			}
			return json;
	}
	
	/**
	 * 注册页面
	 */
	@RequestMapping("register")
	public String register(HttpServletRequest request){
		Protocol protocol = protocolService.selectLatestProtocol();
		request.setAttribute("protocol", protocol);
		return rootPath+"register";
	} 

	/**
	 * 实现注册功能
	 */
	@RequestMapping("checkRegister")
	@ResponseBody
	public JsonObj checkRegister(@RequestParam("type")Integer type,User user,HttpSession session,HttpServletRequest request){
		HashMap<String, Object> map = new HashMap<String, Object>();
		JsonObj json = new JsonObj();
		map.put("type", type);
		User user_ = null;
		String msg = "";
		//ajax实时检测提示
		if(type == 1){
				map.put("username", user.getUserName());
				user_ = userService.selectCheckField(map);
				if(user_ != null){
					msg = "该帐号已被注册,请换一个试试!";
					json.setSuccess(false);
					json.setCode(-1);
				}else{
					msg = "该帐号可以使用!";
					json.setCode(1);
					json.setSuccess(true);
				}
				json.setMessage(msg);
				return json;
		}else if(type == 2){
				map.put("email", user.getEmail());
				user_ = userService.selectCheckField(map);
				if(user_ != null){
					msg = "该邮箱已存在,请换一个试试!";
					json.setSuccess(false);
					json.setCode(-2);
				}else{
					msg = "该邮箱可以使用!";
					json.setSuccess(true);
					json.setCode(2);
				}
				json.setMessage(msg);
				return json;
		}else{
				//直接点击登陆
				map.put("type", 1);
				map.put("username", user.getUserName());
				user_ = userService.selectCheckField(map);
				if(user_ == null){
					//用户名通过在检测邮箱
					map.put("type", 2);
					map.put("email", user.getEmail());
					User u = userService.selectCheckField(map);
					if(u == null){
							String password = MD5.md5(user.getPassword());
							user.setPassword(password);
							user.setIp(IPUtil.getIP(request));
							user.setCreateDate(new Date());
							user.setChName(NameHelper.chName());
							user.setPicture(ImageUtil.getImageBytes());
							boolean success = userService.insertSelective(user);
							if(success){
								String url = "http://" + request.getServerName() //服务器地址  
								+ ":"   
								+ request.getServerPort()           //端口号  
								+ request.getContextPath()   ;   //项目名称  
								url = Constant.BASEPATH + "/registerActivate?username=" + user.getUserName(); //参数  
								url="<a href=\""+url+"\" target=\"_black\">立即激活</a>,如果此处打不开，请将以下地址复制到浏览器中:"+url;
								boolean isSuccess = EmailUtil.sendEmail("注册激活",user.getEmail(),url);
								if(isSuccess){
									msg = "恭喜你,注册成功!系统已自动发邮件到注册的邮箱,请进入邮箱激活";
									json.setCode(0);
									json.setSuccess(true);
									//注册成功发送站内消息
									Msg _msg = new Msg();
									_msg.setMsgTitle(Constant.SUCCESS_REGISTER_TITLE);
									_msg.setMsgContent(Constant.SUCCESS_REGISTER_CONTENT);
									_msg.setCreateDate(new Date());
									_msg.setUserId(Constant.ADMIN_ID);
									msgService.insertAndGetInsertID(_msg);
									UserMsg userMsg = new UserMsg();
									userMsg.setMsgId(_msg.getId());
									userMsg.setUserId(user.getId());
									userMsg.setStatus(0);
									userMsgService.insertSelective(userMsg);
								}else{
									msg = "很遗憾,注册失败你填写的邮件地址无效立即修改!";
									json.setCode(-4);
									json.setSuccess(false);
								}
							}else{
								msg = "很遗憾,注册失败,再来一次吧!";
								json.setSuccess(false);
								json.setCode(-3);
							}
							json.setMessage(msg);
							return json;
					}else{
						msg = "该邮箱已被注册,请换一个试试!";
						json.setMessage(msg);
						json.setSuccess(false);
						json.setCode(-2);
						return json;
					}
				}else{
					msg = "该帐号已被注册,请换一个试试!";
					json.setMessage(msg);
					json.setSuccess(false);
					json.setCode(-1);
					return json;
				}
			}
		
	} 
	
	/**
	 *注册成功发送邮件激活页面，并检验邮箱是否可用
	 */
	@RequestMapping("registerActivate")
	public String registerActivate(String username,HttpServletRequest request){
		request.setAttribute("username",username);
		return rootPath+"registerActivate";
	}
	
	/**
	 *发送邮件激活，更改状态
	 */
	@RequestMapping("registerActivateStatus")
	@ResponseBody
	public JsonObj registerActivateStatus(String username){
		JsonObj jsonObj = new JsonObj();
		User u = userService.login(username);
		u.setDisabled(1);
		boolean success =  userService.updateByPrimaryKeySelective(u);
		if(success){
			jsonObj.setMessage("恭喜你,激活成功!");
			jsonObj.setSuccess(true);
		}else{
			jsonObj.setMessage("很遗憾,激活失败!");
			jsonObj.setSuccess(false);
		}
		return jsonObj;
	}
	
	/**
	 *找回密码页面
	 */
	@RequestMapping("forgetPassword")
	public String forgetPassword(){
		return rootPath+"forgetPassword";
	}
	
	/**
	 *输入邮箱.发送邮件找回密码页面
	 */
	@RequestMapping("updatePwdSendEmail")
	@ResponseBody
	public JsonObj updatePwdSendEmail(String email,HttpServletRequest request){
		JsonObj jsonObj = new JsonObj();
		User u = userService.selectByEmail(email);
		if(u != null){
			//生成密钥
			String secretKey=UUID.randomUUID().toString();
			String content = CreateLink.htmlContent(updateU(u,secretKey),secretKey,request);
			boolean success = EmailUtil.sendEmail("修改密码", email, content);
			if(success){
				jsonObj.setMessage("恭喜你,修改密码邮件发送，请进入邮箱查看!");
				jsonObj.setSuccess(true);
			}else{
				jsonObj.setMessage("很遗憾,邮件发送失败!");
				jsonObj.setSuccess(false);
			}
		}else{
			jsonObj.setMessage("很遗憾,你输入的邮箱不正确!");
			jsonObj.setSuccess(false);
		}
		return jsonObj;
	}
	
	/**
	 * 设置过期日期和code
	 * @return
	 */
	public User updateU(User u,String secretKey){
		//设置过期时间
		Date outDate = new Date(System.currentTimeMillis() + 30 * 60 * 1000);// 30分钟后过期
		u.setOutDate(outDate);
		String validataCode = MD5.md5(u.getUserName() +"$"+outDate+"$"+secretKey);
		u.setValidataCode(validataCode);
		userService.updateByPrimaryKeySelective(u);
		return u;
	}

	@RequestMapping("updatePassword")
	public String updatePassword(Integer id,String sid,HttpServletRequest request){
		User u = userService.selectByPrimaryKey(id);
		if(u != null){
			//链接失效
			if(!u.getValidataCode().equals(sid)){
				request.setAttribute("msg","链接地址已失效,已重新跳转到找回密码页面!");
				return rootPath+"forgetPassword";	
			}
			//链接时间过期
			boolean success = DateUtil.getDistanceTimes(u.getOutDate(), new Date(System.currentTimeMillis()));
			if(!success){//有效
				request.setAttribute("msg","链接地址已失效,已重新跳转到找回密码页面!");
				return rootPath+"forgetPassword";	
			}
		}
		request.setAttribute("id",id);
		return rootPath+"updatePassword";
	}
	
	
	/**
	 *输入邮箱.发送邮件找回密码页面
	 */
	@RequestMapping("updatePwdByEmail")
	@ResponseBody
	public JsonObj updatePwdByEmail(Integer id,String password){
		JsonObj jsonObj = new JsonObj();
		User u = new User();
		u.setPassword(MD5.md5(password));
		u.setId(id);
		boolean success =  userService.updateByPrimaryKeySelective(u);
		if(success){
			jsonObj.setMessage("恭喜你,修改密码成功!");
			jsonObj.setSuccess(true);
		}else{
			jsonObj.setMessage("很遗憾,修改密码失败!");
			jsonObj.setSuccess(false);
		}
		return jsonObj;
	}
	
	
	/**
	 * 退出
	 */
	@RequestMapping("logout")
	public String logout(HttpSession session,HttpServletRequest request){
		User user = (User) session.getAttribute("user");
		if(user != null){
			session.invalidate();
		}
		return  "redirect:index";
	}
}
